package com.usian.article.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.article.fegin.BehaviorFegin;
import com.usian.article.mapper.ApArticleMapper;
import com.usian.article.mapper.ApCollectionMapper;
import com.usian.article.service.ApCollectionService;
import com.usian.model.article.ApArticle;
import com.usian.model.article.ApCollection;
import com.usian.model.article.CollectionBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Autowired
    BehaviorFegin behaviorFegin;
    @Autowired
    ApCollectionMapper apCollectionMapper;
    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult sc(CollectionBehaviorDto dto) {
        //参数校验
        if (dto == null ||dto.getEntryId() ==null ||(dto.getType()<0 && dto.getType()>1) || (dto.getOperation()<0 && dto.getOperation()>1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle findbyid = apArticleMapper.findbyid(dto.getEntryId());
        //查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = behaviorFegin.findByUserIdOrEquipmentId(user.getId());
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApCollection one = apArticleMapper.findone(dto.getEntryId(), apBehaviorEntry.getEntryId());
        if (one == null && dto.getOperation()==0){
            ApCollection apCollection = new ApCollection();
            apCollection.setType(dto.getType());
            apCollection.setCollectionTime(new Date());
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setEntryId(apBehaviorEntry.getEntryId());
            apCollection.setPublishedTime(findbyid.getPublishTime());
            save(apCollection);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else if (one != null && dto.getOperation()==1){
            removeById(one.getId());
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            one.setType(dto.getType());
            updateById(one);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
